import time
import hashlib
import base64
from urllib.parse import urlencode
from common import constants as c


class SignatureTools:

    @staticmethod
    def clear_empty_kv(body_data):
        """剔除字典中值为None or ''的key:value"""
        return {key: value for key, value in body_data.items() if value}

    @staticmethod
    def sort_list(not_empty_data: dict):
        """对字典的键进行排序"""
        return sorted(not_empty_data.keys())

    @staticmethod
    def is_expired_time(req_time: int):
        # 判断超时
        now_time = int(time.time())
        return now_time - req_time > c.EXPIRE_TIME

    @staticmethod
    # 生成签名
    def get_sign_true(app_id: str, app_secret: str, nonce: str, timestamp: str, payload_map: dict) -> str:
        # 创建一个字典
        raw_dict = {
            'app_id': app_id,
            'app_secret': app_secret,
            'nonce': nonce,
            'timestamp': timestamp
        }
        # 去除字典中的空值
        not_empty_dict = SignatureTools.clear_empty_kv(payload_map)
        raw_dict.update(not_empty_dict)
        # 获取字典键排序列表
        sort_list = SignatureTools.sort_list(raw_dict)
        # 构建排序后的字典
        sort_dict = {key: raw_dict[key] for key in sort_list}
        # 将字典数据转为urlencoding编码格式
        encrypt_str = urlencode(sort_dict, doseq=True)
        sha256_hash = hashlib.sha256(encrypt_str.encode()).hexdigest()
        # 将sha256加密后的字符串进行base64编码
        signature = base64.b64encode(sha256_hash.encode()).decode()
        return signature


